import { createLogger } from "@/utils/logger"
import { useUpdateEffect } from "ahooks"
import { isArray, isBoolean, isString } from "lodash"
import { useCallback, useEffect, useState } from "react"
const logger = createLogger("useBetRecord")

// 定义基本的请求参数类型
interface BasePayload {
    page?: number
    page_size?: number
    time_flag?: string
    status?: string
}

// 定义基本的返回结果类型
interface BaseResult<C extends object[]> {
    list?: C
    page_size?: number
    hasMore?: boolean
    total?: number
}

function usePage<P extends BasePayload, C extends object, R extends BaseResult<C[]>>(
    api: (payload?: P) => Promise<R>, // 泛型 api，返回值为 R 类型
    payload: P,
) {
    const [page, setPage] = useState<number>(1)
    const [hasMore, setHasMore] = useState<boolean>(true)
    const [list, setList] = useState<C[]>([])
    const [isLoading, setIsLoading] = useState<boolean>(false)
    const [result, setResult] = useState<R>()
    const [total, setTotal] = useState<number>(0)

    const getList = useCallback(async () => {
        if (isLoading) {
            return
        }
        try {
            setIsLoading(true)
            if (!payload.status) {
                delete payload.status
            }
            const res = await api({ ...payload, page })
            setResult(res)

            // 计算是否还有更多数据
            const _pageSize = payload.page_size || 0
            const _total = res?.total || 0
            const hasMore = page * _pageSize < _total

            if (isBoolean(hasMore)) {
                setHasMore(hasMore)
            }

            const nextList = res.list ?? []
            setList((prev) => [...prev, ...nextList])
            setPage(hasMore ? page + 1 : page)
            setTotal(_total)
        } catch (err) {
            logger.debug("usePage", err)
        } finally {
            setIsLoading(false)
        }
    }, [payload, isLoading, api, page])

    useEffect(() => {
        return () => {
            setList([]) // 清除列表
            setIsLoading(false) // 重置加载状态
            setHasMore(true) // 重置加载更多状态
        }
    }, [payload])

    useUpdateEffect(() => {
        // 当 payload 变化时，重置状态并加载第一页
        setPage(1)
        setList([])
        setHasMore(true)
    }, [payload.status, payload.time_flag])

    useUpdateEffect(() => {
        if (hasMore) {
            getList()
        }
    }, [payload, hasMore])

    return { result, list: isArray(list) ? list : [], hasMore, isLoading, getList, total }
}

export default usePage
